package com.yhp.mvc;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

@WebServlet(name = "DispatcherServlet", value = "/DispatcherServlet")
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfigLocation");
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandLerMapping.load(is);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求地址
        String uri = req.getRequestURI();
        System.out.println("servlet>>>"+uri);
        //根据请求地址获取  值    map集合的键值对   地址是键   获取的是值（对象）
        HandLerMapping.MVCMapping mvcMapping = HandLerMapping.get(uri);
        //如果没有获取到 对象的话  返回给前台 错误
        if(mvcMapping == null){
            resp.sendError(404,"自定义mvc映射地址不存在"+uri);
            return;
        }
        //获取到mapping类里面的值
        Object obj = mvcMapping.getObj();   //对象
        Method method = mvcMapping.getMethod();   //方法
        String result = null;
        try {
            //执行这个方法
            result = (String) method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //判断取过来的对象是什么类型
        switch (mvcMapping.getType()){
            //内容
            case TEXT:
                PrintWriter writer = resp.getWriter();
                writer.write(result);
                break;

            //页面
            case VIEW:
                resp.sendRedirect(result);
                break;
        }
    }
}
